package com.pointi.emoConverterM;

import java.util.ArrayList;
import java.util.concurrent.ConcurrentLinkedQueue;

import com.pointi.emoGatewayM.AliveInfo;
import com.pointi.emoGatewayM.JDBC;

public class ThreadScheduler extends Thread
{
	//____________________________________________________________________________________________________
	// DEF
	
	private ConcurrentLinkedQueue<ThreadScheduler> _Scheduler ;
	private JDBC _JDBC ;
	private AliveInfo _AliveInfo ;
	private int CheckInterval = 1000 ;

	//____________________________________________________________________________________________________
	// INIT
	
	public ThreadScheduler(ConcurrentLinkedQueue<ThreadScheduler> inThread)
	{
		_Scheduler = inThread ;
	}

	public void start(JDBC inJDBC, AliveInfo inAliveInfo, int inCheckInterval)
	{
		CheckInterval = inCheckInterval ;
		_JDBC = inJDBC ;
		_AliveInfo = inAliveInfo ;
		_Scheduler.add(this) ;
		super.start();
	}
	
	//____________________________________________________________________________________________________
	// RUN // Work Schedule Builder

	public void run()
	{
		try
		{
			ArrayList<String> _AliveServer = new ArrayList<String>() ;
			ArrayList<String> _AliveClient = new ArrayList<String>() ;
			ArrayList<String> _ConvertedFile = new ArrayList<String>() ;

			boolean loop = true ;
			while(loop)
			{
				_JDBC.fnGetServerStatus(_AliveServer) ;
				_JDBC.fnGetClientStatus(_AliveClient) ;
				_JDBC.fnGetConvertedList(_ConvertedFile) ;
				System.out.println(String.format("[GW][WKS] Alive Server(S:%d) | Alive Client(C:%d) | Converted File(F:%d)", _AliveServer.size(), _AliveClient.size(), _ConvertedFile.size())) ;

				if (_ConvertedFile.size() > 0)
				{
					int sizeT = _ConvertedFile.size() ;
					int sizeC = _AliveClient.size() ;
					int sizeS = _AliveServer.size() ;
					int nextC = _AliveInfo.clientIndex ;
					int nextS = _AliveInfo.serverIndex ;
					String inCallKey = null ;
					String inClientNo = null ;
					String inServerNo = null ;

					for (int i=0; i<sizeT; i++) // All Converted File
					{
						inClientNo = _AliveClient.get(nextC) ; nextC++ ;
						inServerNo = _AliveServer.get(nextS) ; nextS++ ;
						if (nextC >= sizeC) nextC = 0 ;
						if (nextS >= sizeS) nextS = 0 ;

						// Set Converted File
						inCallKey = _ConvertedFile.get(0) ;
						_ConvertedFile.remove(0) ;
						_JDBC.fnInsertWorkSchedule(inCallKey, inClientNo, inServerNo);

						System.out.println("[GW][WKS] Create Work Schedule (Callkey : " + inCallKey + " | Client : " + inClientNo + " | Server : " + inServerNo + ")") ;
					}
					_AliveInfo.clientIndex = nextC ;
					_AliveInfo.serverIndex = nextS ;
				}
				Thread.sleep(CheckInterval) ;
			}
		}
		catch (Exception e) { e.printStackTrace() ; }
		_Scheduler.remove(this) ;
	}
	
	//____________________________________________________________________________________________________
	// EOC
}